/**
 * 
 */
package userLogic;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import mail.MailSender;

import org.apache.commons.lang3.StringUtils;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import constants.Constants;
import rentReturnEntity.PointsRedeemedEntity;
import userController.MembershipController;
import userController.Navigator;
import userEntity.MembershipEntity;
import userEntity.MembershipRenewalEntity;
import userEntity.ViewMembershipEntity;
import userService.MembershipService;
import vehicleEntity.PurchasedVehicleDisplay;
import vehicleEntity.SaleVehicleEntity;
import vehicleEntity.VehicleDisplayable;

/**
 * @author Yokesh Kumar
 *
 */
public class MembershipLogic {

	/**
	 * This method populates membership entity values
	 * returns the membership iD
	 * @param paymentId
	 * @param phoneNumber
	 * @return
	 */
	public int createMembership(int paymentId){
		// load membershipEntity values 
		MembershipEntity membershipEntity = new MembershipEntity();
		ResultSet rs= null;
		int membershipId = 0;
		membershipEntity.setJoinPaymentId(paymentId);
		membershipEntity.setJoiningFee(Constants.NEW_MEMBERSHIP_AMOUNT);
		membershipEntity.setPoints(Constants.INITIAL_MEMBERSHIP_POINTS);
		membershipEntity.setStatus(Constants.MEMBERSHIP_ACTIVE);
		membershipEntity.setPhoneNumber(Navigator.getPhoneNumber());
		MembershipService service = new MembershipService();
		try{
			rs = service.createMembership(membershipEntity);
			if(rs != null && rs.next()){
				membershipId = rs.getInt("last_id");
				if(membershipId != 0){
					service.updateCustomerIsMember(Navigator.getPhoneNumber(),Constants.MEMBER);
					service.transactionCommit();
					String emailid = fetchEmailID(Navigator.getPhoneNumber());
					if(emailid != null && !StringUtils.isEmpty(emailid)){
						String text = "Dear Customer, Your Superrent club membership is successfully created. Your payment Id " + paymentId + " .Your Membership Id ." + membershipId +" .Your current points = 500";
						String subject = "Welcome to superrent club membership";
						MailSender.send(text, subject, emailid);
					}
				}
				else{
					service.transactionRollBack();
				}
			}
			else{
				System.out.println("membership id not returned");
				
			}
			service.closeConnection();
		}
		catch(SQLException sqlExce){
			sqlExce.printStackTrace();
		}
		return membershipId;
	}
	
	/**
	 * This method cancels the membership of the customer
	 * @param membershipId
	 * @param cancelDesc
	 * @return
	 */
	public String cancelMemberShip(int membershipId, String cancelDesc){
		MembershipService service = new MembershipService();
		String message = "";
		try{
			service.cancelMembership(membershipId,cancelDesc);
			service.updateMembershipStatus(membershipId, Constants.MEMBERSHIP_INACTIVE);
			service.updateCustomerIsMember(Navigator.getPhoneNumber(), false);
			message = "Membership cancelled successfully. Thanks for using SuperRent Club Membership";
			service.transactionCommit();
			String emailid = fetchEmailID(Navigator.getPhoneNumber());
			if(emailid != null && !StringUtils.isEmpty(emailid)){
				String text = "Your Membership " + membershipId +" cancelled successfully. Thanks for using SuperRent Club Membership";
				String subject = "Superrent club membership Cancelled";
				MailSender.send(text, subject, emailid);
			}
			
		}
		catch(SQLException sqlExec){
			try {
				service.transactionRollBack();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			sqlExec.printStackTrace();
			message = "Couldn't cancel membership. Please try again";
			
		}
		service.closeConnection();
		return message;
	}
	
	/**
	 * This method inserts the membership renewal details, returns the renewal ID
	 * @param paymentId
	 * @param phoneNumber
	 * @param memberShipId
	 * @return
	 */
	public int renewMembership(int paymentId){
		MembershipService service = new MembershipService();
		int renewalId = 0;
		Calendar cal = Calendar.getInstance();
		if(!MembershipController.getMembership().getStatus().equalsIgnoreCase(Constants.MEMBERSHIP_EXPIRED)){
			cal.setTime(MembershipController.getMembership().getExpirydate());
		    cal.add(Calendar.YEAR,1);
		}
		else{
			cal.add(Calendar.YEAR,1);
		}
	    MembershipRenewalEntity renewalEntity = new MembershipRenewalEntity();
	    renewalEntity.setCustphoneNumber(Navigator.getPhoneNumber());
	    renewalEntity.setMembershipId(MembershipController.getMembership().getMemberShipId());
	    renewalEntity.setPaymentId(paymentId);
	    renewalEntity.setRenewalAmount(Constants.RENEW_MEMBERSHIP_AMOUNT);
	    
	    java.sql.Date expDate = new java.sql.Date(cal.getTime().getTime());
		try {
			service.updateExpiryDate(expDate,MembershipController.getMembership().getMemberShipId());
			ResultSet rs = service.renewMembership(renewalEntity);
			if(rs != null && rs.next()){
				renewalId = rs.getInt("last_id");
				if(renewalId != 0){
					service.transactionCommit();
					String emailid = fetchEmailID(Navigator.getPhoneNumber());
					if(emailid != null && !StringUtils.isEmpty(emailid)){
						SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
						String text = "Your Membership " + renewalEntity.getMembershipId() +" renewed successfully.Your payment Id " + paymentId + " . Membership expiry date - " + format.format(expDate);
						String subject = "Superrent club membership Renewed";
						MailSender.send(text, subject, emailid);
					}
				}
				else{
					service.transactionRollBack();
				}
			}
			else{
				System.out.println("renewalId not returned");
				service.transactionRollBack();
			}
		} 
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		service.closeConnection();
		return renewalId;
	}
	
	/**
	 * This method fetches the points history of the customer
	 * @param memberShipId
	 * @return
	 * @throws SQLException 
	 */
	/*public List<PointsRedeemedEntity> fetchMembershipPonitsHistory(int memberShipId){
		
		return null;
	}*/
	
	/**
	 * This method fetches the details from the tables and sets it to the resultSet
	 * @param membershipId
	 * @Pre membershipId retrieved from MembershipController class
	 * @Post membershipId passed to the MembershipService class
	 * @return list
	 * @throws SQLException
	 */
	public ObservableList<ViewMembershipEntity> fetchMembershipPointsHistory(Integer membershipId) throws SQLException{
		System.out.println("Inside Logic Class");
		MembershipService memservice = new MembershipService();
		System.out.println("Membership ID retrieved from logic is "+membershipId);
		ResultSet membershipListResultSet = memservice.fetchMembershipPointsHistory(membershipId);	
		ObservableList<ViewMembershipEntity> list = FXCollections.observableArrayList();
		
		try
		{
			while(membershipListResultSet.next())
			{
				ViewMembershipEntity membershipEntity = new ViewMembershipEntity();
				membershipEntity.setRentId(membershipListResultSet.getInt("RentId"));
				membershipEntity.setRentDate(membershipListResultSet.getDate("rentDate"));
				membershipEntity.setReturnDate(membershipListResultSet.getDate("returnDate"));
				membershipEntity.setVehicleType(membershipListResultSet.getString("vehicleType"));
				membershipEntity.setVehicleName(membershipListResultSet.getString("VehicleName"));
				membershipEntity.setPointsRedeemed(membershipListResultSet.getInt("pointsRedeemed"));
				membershipEntity.setPointsGained(membershipListResultSet.getInt("pointsGained"));
				System.out.println(membershipEntity.getRentDate());
			  list.add(membershipEntity);
			}
		}
	
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return list;
	}
	/**
	 * @return
	 */
	public String calculateExpiryDays(MembershipEntity membership) {
		String message= "";
		if(membership != null){
			Calendar cal = new GregorianCalendar();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			String curentDate = format.format(cal.getTime());
			Date currDate = null;
			try {
				currDate = format.parse(curentDate);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			long diff = membership.getExpirydate().getTime() - currDate.getTime();
			if(diff > 0){
				long days = diff/(24*60*60*1000);
				message = days+ " days";
			}
			else{
				message = "Membership already expired. Please renew memberhship" ;
 			}
		}
		else{
			System.out.println("calculateExpiryDays method : Navigator.membership is null");
		}
		return message;
	}

	/**
	 * 
	 */
	public void checkForExpiry(MembershipEntity memberEntity) {
		Calendar cal = new GregorianCalendar();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String curentDate = format.format(cal.getTime());
		Date currDate = null;
		try {
			currDate = format.parse(curentDate);
		if(!memberEntity.getExpirydate().after(currDate)){
			MembershipService service = new MembershipService();
			service.updateMembershipStatus(memberEntity.getMemberShipId(), Constants.MEMBERSHIP_EXPIRED);
			MembershipController.getMembership().setStatus(Constants.MEMBERSHIP_EXPIRED);
			service.transactionCommit();
			service.closeConnection();
		}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	public String fetchEmailID(String phNo) throws SQLException{
		MembershipService service = new MembershipService();
		ResultSet rs = null;
		String emailId ="";
		try {
			rs = service.fetchEmailID(phNo);
			if(rs.next()){
				emailId = rs.getString("emailID");
			}
			service.closeConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			service.closeConnection();
			throw e;
		}
		return emailId;
	}
}
